package com.fenxiangle.yueding.feature.order.view;


import android.Manifest;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fenxiangle.yueding.R;
import com.fenxiangle.yueding.entity.bo.CommentBo;
import com.fenxiangle.yueding.entity.bo.EventEntity;
import com.fenxiangle.yueding.entity.bo.PageBo;
import com.fenxiangle.yueding.entity.bo.PublishDemandBo;
import com.fenxiangle.yueding.entity.bo.TabEntity;
import com.fenxiangle.yueding.entity.bo.TeamBo;
import com.fenxiangle.yueding.entity.bo.UnMsgBo;
import com.fenxiangle.yueding.entity.bo.UnReadCountBo;
import com.fenxiangle.yueding.entity.bo.UserImageBo;
import com.fenxiangle.yueding.feature.home.view.UserInfoActivity;
import com.fenxiangle.yueding.feature.mine.view.adapter.Share2Activity;
import com.fenxiangle.yueding.feature.order.contract.OrderContract;
import com.fenxiangle.yueding.feature.order.dependencies.order.DaggerOrderComponent;
import com.fenxiangle.yueding.feature.order.dependencies.order.OrderPresenterModule;
import com.fenxiangle.yueding.feature.order.view.adapter.MyRatingAdapter;
import com.fenxiangle.yueding.feature.order.view.adapter.OrderAdapter;
import com.fenxiangle.yueding.framework.api.HomeApi;
import com.fenxiangle.yueding.framework.api.UserApi;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.flyco.tablayout.utils.UnreadMsgUtils;
import com.flyco.tablayout.widget.MsgView;
import com.luck.picture.lib.rxbus2.RxBus;
import com.luck.picture.lib.rxbus2.Subscribe;
import com.luck.picture.lib.rxbus2.ThreadMode;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.suozhang.framework.component.http.RxDataProcessFactory;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseFragment;
import com.suozhang.framework.utils.T;
import com.suozhang.framework.widget.EmptyView;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.leolin.shortcutbadger.ShortcutBadger;

import static android.content.Context.CLIPBOARD_SERVICE;

/**
 * A simple {@link Fragment} subclass.
 */
public class OrderFragment extends BaseFragment implements OrderContract.View, OnRefreshListener,
        BaseQuickAdapter.RequestLoadMoreListener,
        BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener, RadioGroup.OnCheckedChangeListener, OnTabSelectListener {


    @BindView(R.id.tv_order_show)
    TextView mTvOrderShow;
    @BindView(R.id.rv_order)
    RecyclerView mRvOrder;
    @BindView(R.id.smartRefesh)
    SmartRefreshLayout mSmartRefesh;

    @BindView(R.id.rv_publish_rating)
    RecyclerView mRvPublishRating;
    @BindView(R.id.rgp_all)
    RadioGroup mRgpAll;
    Unbinder unbinder;
    @BindView(R.id.tab_menu)
    CommonTabLayout mTabMenu;
    private OrderAdapter mAdapter;
    private EmptyView mEmptyView;
    private EmptyView mEmptyViewRating;
    private int pageIndex = 1;
    private int pageSize = 10;
    List<PublishDemandBo> mData;
    MyRatingAdapter ratingAdapter;
    private String mOrderStatus = null;
    @Inject
    OrderContract.Presenter mPresenter;

    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();

    private String[] mTitles = {"全部订单", "交易中", "待确认", "已完成", "我的评分"};
    private int[] mIconUnselectIds = {
            R.drawable.ic_order_all, R.drawable.ic_order_trading,
            R.drawable.ic_order_daiqueren, R.drawable.ic_order_complete, R.drawable.ic_order_daipingfen};

    private int[] mIconSelectIds = {
            R.drawable.ic_order_all, R.drawable.ic_order_trading,
            R.drawable.ic_order_daiqueren, R.drawable.ic_order_complete, R.drawable.ic_order_daipingfen};
    private CallBackValue callBackValue;

    @Override
    public int attachLayoutRes() {
        return R.layout.fragment_order;
    }

    /**
     * fragment与activity产生关联是  回调这个方法
     */
    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        //当前fragment从activity重写了回调接口  得到接口的实例化对象
        callBackValue =(OrderFragment.CallBackValue) getActivity();
    }

    @Override
    protected void initInjector() {
        DaggerOrderComponent.builder().orderPresenterModule(new OrderPresenterModule(this)).build().inject(this);
    }

    @Override
    public void toComments(String s) {

    }

    @Override
    public void confirmOrder(String s) {

    }

    @Override
    public void showUserListSuccess(List<TeamBo> workBoPageData) {

    }

    @Override
    public void showSheetSuccess(UserImageBo workBoPageData) {

    }

    @Override
    public void showcancleSheetSuccess(UserImageBo workBoPageData) {

    }

    @Override
    public void showPublishListSuccess(List<PublishDemandBo> workBoPageData) {
        mSmartRefesh.finishRefresh();
        mData = workBoPageData;
        setData(true, mData);
        mAdapter.setEnableLoadMore(true);
    }

    @Override
    public void showSheetListSuccess(List<PublishDemandBo> workBoPageData) {

    }

    @Override
    public void showPublishListError(String error) {
        if (mSmartRefesh != null) mSmartRefesh.finishRefresh();
        mAdapter.setEmptyView(mEmptyView.getErrorView(error));
        mAdapter.setNewData(null);
        mAdapter.setEnableLoadMore(true);
        mSmartRefesh.finishRefresh();
    }

    @Override
    public void showPublishListMoreSuccess(List<PublishDemandBo> msg) {
        setData(false, msg);
    }

    @Override
    public void showPublishListMoreError(String msg) {
        mAdapter.loadMoreFail();
    }

    @Override
    public void showPublishListEmpty() {
        if (mSmartRefesh != null) mSmartRefesh.finishRefresh();
        mAdapter.setEmptyView(mEmptyView.getEmptyView());
        mAdapter.setNewData(null);
    }

    @Override
    public void showAcceptSuccess(String s) {
        mSmartRefesh.autoRefresh();
    }

    @Override
    public void showRefuseSuccess(String s) {
        showMsg("拒绝成功!");
        mSmartRefesh.autoRefresh();
    }

    @Override
    public void showError(String error) {
        showMsg(error);
    }

    @Override
    public void showConfrimTxSuccess() {
        showMsg("提醒成功!");
    }

    @Override
    public void showAppealTxSuccess(String s) {

    }

    @Override
    public void showCancleSuccess() {
        showMsg("取消成功!");
        mSmartRefesh.autoRefresh();
    }

    private void initTabMsg() {


        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]));
        }

        mTabMenu.setTabData(mTabEntities);
        mTabMenu.setOnTabSelectListener(this);





    }

    public void initAdapter() {
        mSmartRefesh.setEnableLoadMore(false);
        mSmartRefesh.setOnRefreshListener(this);
        mEmptyView = new EmptyView(mRvOrder);
        mRvOrder.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new OrderAdapter();
        mAdapter.bindToRecyclerView(mRvOrder);
        mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT);
        mAdapter.setOnLoadMoreListener(this, mRvOrder);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnItemChildClickListener(this);
    }

    @Override
    protected void initView() {

        initTabMsg();
        if (!RxBus.getDefault().isRegistered(this)) {
            RxBus.getDefault().register(this);
        }
        initAdapter();
        initRatingAdapter();
        mRgpAll.check(R.id.btn_order_all);
    }

    @Override
    public void onStart() {
        super.onStart();
        mSmartRefesh.autoRefresh();
    }


    @Override
    protected void initData() {
        pageIndex = 1;
        mPresenter.getOrderList(pageIndex, pageSize, mOrderStatus);
        getMsgCount();
        callBackValue.selectCount(true);
    }

    @Override
    protected void initEvent() {
        mRgpAll.setOnCheckedChangeListener(this);
    }

    private void setData(boolean isRefresh, List data) {
        pageIndex++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mAdapter.setNewData(data);
        } else {
            if (size > 0) {
                mAdapter.addData(data);
            }
        }
        if (size < pageSize) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(isRefresh);
        } else {
            mAdapter.loadMoreComplete();
        }
    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }


    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refresh();
    }

    @Override
    public void onLoadMoreRequested() {
        loadMore();
    }


    private void refresh() {
        mAdapter.setEnableLoadMore(false);
        initData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventBus(EventEntity obj) {
        switch (obj.what) {
            case 999:
            case 55:
                mSmartRefesh.autoRefresh();
                break;
        }
    }

    private void loadMore() {
        mPresenter.getOrderListMore(pageIndex, pageSize, mOrderStatus);
    }

    /**
     * JD("接单 ", 0),
     * QXJY("取消交易", 3),
     * TXQR("提醒确认", 4),
     * TJZL("提交资料", 6);
     */

    private ClipboardManager myClipboard;
    private ClipData myClip;
    RxPermissions rxPermissions;

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()) {
            case R.id.btn_state:
                switch (mData.get(position).getOrderStatus()) {
                    case 0:
                        mPresenter.acceptOrder(mData.get(position).getOrderId());
                        break;
                    case 3:
                        mPresenter.cancleOrder(mData.get(position).getOrderId(),mData.get(position).getType()+"");
                        break;
                    case 4:
                        mPresenter.txOrder(mData.get(position).getOrderId());
                        break;
                    case 6:
                        Intent intentaa = new Intent(getActivity(), Share2Activity.class);
                        startActivity(intentaa);
                        break;
                }
                break;
            case R.id.btn_call_phone:

                rxPermissions = new RxPermissions(getActivity());
                rxPermissions
                        .request(Manifest.permission.CALL_PHONE)
                        .subscribe(granted -> {
                            if (granted) { // Always true pre-M
                                diallPhone(mData.get(position).getUserPhone());
                            } else {
                                showMsg("请先开启拨打电话权限!");
                            }
                        });
                break;
            case R.id.btn_copy_wx:
                if (TextUtils.isEmpty(mData.get(position).getWeChat())) {
                    T.showShort("该用户未设置微信号！");
                } else {
                    myClipboard = (ClipboardManager) getActivity().getSystemService(CLIPBOARD_SERVICE);
                    myClip = ClipData.newPlainText("text", mData.get(position).getWeChat());
                    myClipboard.setPrimaryClip(myClip);
                    T.showShort("文本已复制！");
                }
                break;

            case R.id.iv_my_publish_head:
            case R.id.tv_my_publish_username:
                Intent intent = new Intent(getActivity(), UserInfoActivity.class);
                intent.putExtra("id", mData.get(position).getUserUid());
                startActivity(intent);
                break;
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (!RxBus.getDefault().isRegistered(this)) {
            RxBus.getDefault().unregister(this);
        }
    }


    private void initRatingAdapter() {
        mRvPublishRating.setLayoutManager(new LinearLayoutManager(getActivity()));
        ratingAdapter = new MyRatingAdapter();
        mEmptyViewRating = new EmptyView(mRvPublishRating);
        ratingAdapter.bindToRecyclerView(mRvPublishRating);
    }

    protected void initRatingData() {
        AM.api().createApiService(UserApi.class)
                .getScore(new PageBo(1, 100, ""))
                .compose(RxDataProcessFactory.dataPrepAndIoToMainTransformer())
                .subscribe(new Observer<List<CommentBo>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        showLoading(d);
                    }

                    @Override
                    public void onNext(List<CommentBo> commentBo) {
                        dismissLoading();
                        if (commentBo != null && commentBo.size() > 0) {
                            ratingAdapter.setNewData(commentBo);
                        } else {
                            ratingAdapter.setEmptyView(mEmptyViewRating.getEmptyView());
                            ratingAdapter.setNewData(null);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoading();
                        mEmptyViewRating.getErrorView(e.getMessage());
                        ratingAdapter.setNewData(null);
                    }

                    @Override
                    public void onComplete() {
                        dismissLoading();
                    }
                });
    }

    public void diallPhone(String phoneNum) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_CALL);
        //url:统一资源定位符
        //uri:统一资源标示符（更广）
        intent.setData(Uri.parse("tel:" + phoneNum));
        //开启系统拨号器
        startActivity(intent);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {

    }


    @Override
    public void onTabSelect(int position) {
        mTvOrderShow.setText(mTitles[position]);
        switch (position) {
            case 0:
                mOrderStatus = null;
                initData();
                mSmartRefesh.setVisibility(View.VISIBLE);
                mRvPublishRating.setVisibility(View.GONE);
                break;
            case 1:

                mOrderStatus = "3";
                initData();
                mSmartRefesh.setVisibility(View.VISIBLE);
                mRvPublishRating.setVisibility(View.GONE);
                break;
            case 2:
                mOrderStatus = "4";
                initData();
                mSmartRefesh.setVisibility(View.VISIBLE);
                mRvPublishRating.setVisibility(View.GONE);
                break;
            case 3:
                mOrderStatus = "1,5";
                initData();
                mSmartRefesh.setVisibility(View.VISIBLE);
                mRvPublishRating.setVisibility(View.GONE);
                break;
            case 4:
                mSmartRefesh.setVisibility(View.GONE);
                mRvPublishRating.setVisibility(View.VISIBLE);
                initRatingData();
                break;


        }
    }

    @Override
    public void onTabReselect(int position) {

    }


    private void getMsgCount() {
        AM.api().createApiService(HomeApi.class)
                .selectDiffMessageCount(new UnMsgBo(3 + ""))
                .compose(RxDataProcessFactory.dataPrepAndIoToMainTransformer())
                .subscribe(new Observer<UnReadCountBo>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(UnReadCountBo msgBos) {
                        if (msgBos != null) {

                            if (msgBos.getMyAcceptTrading() > 0) {

                                //两位数
                                mTabMenu.showMsg(1, msgBos.getMyAcceptTrading());
                                mTabMenu.setMsgMargin(1, -8, 5);

                                MsgView rtv_2_3 = mTabMenu.getMsgView(1);
                                if (rtv_2_3 != null) {
                                    rtv_2_3.setStrokeColor(getResources().getColor(R.color.yuffff4b28));
                                    rtv_2_3.setBackgroundColor(getResources().getColor(R.color.yuffff4b28));
                                    rtv_2_3.setTextColor(getResources().getColor(R.color.bg_060000));
                                    rtv_2_3.setTextSize(10);
                                    DisplayMetrics dm = rtv_2_3.getResources().getDisplayMetrics();
                                    int size = (int) (14 * dm.density);
                                    UnreadMsgUtils.setSize(rtv_2_3, size);
                                }
                            }

                            if (msgBos.getMyAcceptWaitingConfirm() > 0) {

                                //三位数
                                mTabMenu.showMsg(2, msgBos.getMyAcceptWaitingConfirm());
                                mTabMenu.setMsgMargin(2, -8, 5);

                                MsgView rtv_2_4 = mTabMenu.getMsgView(2);
                                if (rtv_2_4 != null) {
                                    rtv_2_4.setStrokeColor(getResources().getColor(R.color.yuffff4b28));
                                    rtv_2_4.setBackgroundColor(getResources().getColor(R.color.yuffff4b28));
                                    rtv_2_4.setTextColor(getResources().getColor(R.color.bg_060000));
                                    rtv_2_4.setTextSize(10);
                                    DisplayMetrics dm = rtv_2_4.getResources().getDisplayMetrics();
                                    int size = (int) (14 * dm.density);
                                    UnreadMsgUtils.setSize(rtv_2_4, size);
                                }
                            }

                        }

                        if(msgBos.getUserCenterTotal()>0){
                            ShortcutBadger.applyCount(getActivity(), msgBos.getUserCenterTotal());
                        }else {
                            ShortcutBadger.removeCount(getActivity());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //定义一个回调接口
    public interface CallBackValue{

        public void selectCount(boolean isSelect);
    }
}
